package com.jet.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jet.core.utils.IdUtil;
import com.jet.member.domain.dto.MemberRechargeOrderDto;
import com.jet.member.domain.entity.MemberRechargeOrder;
import com.jet.member.domain.query.MemberRechargeOrderSummaryQuery;
import com.jet.member.mapper.MemberRechargeOrderMapper;
import com.jet.member.service.IMemberRechargeOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-02
 */
@Service
public class MemberRechargeOrderServiceImpl extends ServiceImpl<MemberRechargeOrderMapper, MemberRechargeOrder> implements IMemberRechargeOrderService {

    @Override
    public void create(long merchantNo, long storeNo, MemberRechargeOrderDto dto) {
        MemberRechargeOrder entity = new MemberRechargeOrder();
        BeanUtils.copyProperties(dto, entity);
        entity.setId(IdUtil.generateLower());
        entity.setMerchantNo(merchantNo);
        entity.setStoreNo(storeNo);
        entity.setRefunded(0);
        if (entity.getRechargeTime() == null) {
            entity.setRechargeTime(LocalDateTime.now());
        }
        super.save(entity);
    }

    @Override
    public void refund(long merchantNo, String orderNo, LocalDateTime refundTime) {
        if (refundTime == null) {
            refundTime = LocalDateTime.now();
        }
        Wrapper<MemberRechargeOrder> wrapper = new LambdaQueryWrapper<MemberRechargeOrder>()
                .eq(MemberRechargeOrder::getMerchantNo, merchantNo)
                .eq(MemberRechargeOrder::getOrderNo, orderNo);
        MemberRechargeOrder entity = new MemberRechargeOrder();
        entity.setRefunded(1);
        entity.setRefundTime(refundTime);
        super.update(entity, wrapper);
    }

    @Override
    public List<MemberRechargeOrder> summaryList(MemberRechargeOrderSummaryQuery query) {
        if (query.getEndDate() != null) {
            query.setEndDate(query.getEndDate().plusDays(1));
        }
        query.setRefunded(0); // 未退款
        Wrapper<MemberRechargeOrder> wrapper = new LambdaQueryWrapper<MemberRechargeOrder>()
                .eq(MemberRechargeOrder::getMerchantNo, query.getMerchantNo())
                .eq(MemberRechargeOrder::getRefunded, query.getRefunded())
                .eq(query.getStoreNo() != null, MemberRechargeOrder::getStoreNo, query.getStoreNo())
                .ge(query.getStartDate() != null, MemberRechargeOrder::getRechargeTime, query.getStartDate())
                .lt(query.getEndDate() != null, MemberRechargeOrder::getRechargeTime, query.getEndDate())
                .orderByDesc(MemberRechargeOrder::getRechargeTime);
        return super.list(wrapper);
    }
}
